﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Foundation;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using Vent.ViewModels.Tools;

namespace Vent.ViewModels
{
    public class CanvasViewModel : ViewModel
    {
        private PhotoChooserTask _photoChooserTask;

        public CanvasViewModel()
        {
            Initialize();
        }

        private TouchViewModel TouchViewModel { get; set; }

        [OnDeserialized]
        public new void Initialize(StreamingContext context = default (StreamingContext))
        {
            TouchViewModel = Store.OfType<TouchViewModel>();

            var tool0 = Serializer.DeserializeDataContract<PolylineTool>("tool0.json") ?? new PolylineTool();
            var tool1 = Serializer.DeserializeDataContract<PolylineTool>("tool1.json") ?? new PolylineTool();
            var tool2 = Serializer.DeserializeDataContract<MaskTool>("tool2.json") ?? new MaskTool();

            tool0.Name = "Polyline";
            tool1.Name = "Water";
            tool2.Name = "Mask";
            tool0.Water = false;
            tool1.Water = true;
            tool2.Water = false;

            TouchViewModel.Tools.Add(tool0);
            TouchViewModel.Tools.Add(tool2);
            TouchViewModel.Tools.Add(tool1);

            Application.Current.Exit += (sender, args) =>
            {
                tool0.SerializeDataContract("tool0.json");
                tool1.SerializeDataContract("tool1.json");
                tool2.SerializeDataContract("tool2.json");
                Store.Snapshot();
            };

            _photoChooserTask = new PhotoChooserTask {ShowCamera = true};
            _photoChooserTask.Completed += (o, result) =>
            {
                if (result.TaskResult != TaskResult.OK) return;
                var bmp = new BitmapImage();
                bmp.SetSource(result.ChosenPhoto);
                TouchViewModel.Background = new ImageBrush {ImageSource = bmp};
            };

            this[SharedCommands.New].Executed += (sender, args) => TouchViewModel.Clear();
            this[SharedCommands.Open].Executed += (sender, args) =>
            {
                if (args.Parameter != null)
                {
                    var imageSource = new BitmapImage(new Uri(args.Parameter.ToString(), UriKind.Relative));
                    TouchViewModel.Background = new ImageBrush
                    {
                        ImageSource = imageSource,
                        AlignmentX = AlignmentX.Left,
                        AlignmentY = AlignmentY.Top,
                        Stretch = Stretch.None
                    };
                }
                else _photoChooserTask.Show();
            };

            this[SharedCommands.Save].Executed += (sender, args) =>
            {
                try
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        const string fileName = "tmp.jpg";

                        using (var fileStream = store.OpenFile(fileName, FileMode.OpenOrCreate))
                        {
                            var bitmap = new WriteableBitmap(TouchViewModel.Canvas, null);
                            bitmap.SaveJpeg(fileStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                        }

                        using (var fileStream = store.OpenFile(fileName, FileMode.Open))
                        {
                            using (var library = new MediaLibrary())
                            {
                                library.SavePicture(fileName, fileStream);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            };
        }
    }
}